const app=getApp()
const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('-')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}
function login() {
    return new Promise((resolve,reject)=>{
    wx.showModal({
      title: '是否匿名登录',
      content: '匿名登录将不会获取你的信息',
      success: (res)=>{
        if (res.confirm) {
          app.globalData.userInfo={nickName:"匿名用户",avatarUrl:"/image/head.png"}
          resolve()
        } else if (res.cancel) {
          wx.getUserProfile({
                  desc: '必须授权才可以继续使用',
                  success:res => {
                    console.log(res)
                   var user=res.userInfo;
                      app.globalData.userInfo=user;
                      //上传用户信息到数据库
                      //要检查是否之前登录过
                      wx.cloud.database().collection('login_user').where({
                        _openid:app.globalData.openid
                      }).get({
                        success(res){
                          //如果找不到，则添加进数据库
                          if(res.data.length==0){
                            wx.cloud.database().collection('login_user').add({
                              data:{
                                avatarUrl:user.avatarUrl,
                                nickName:user.nickName
                              },
                            })
                          }else{
                          //  找到了，则直接拿数据库的数据，不作插入操作
                          app.globalData.userInfo=res.data[0]
                          }
                          wx.showToast({
                            title: '登录成功',
                            icon:'none',
                            duration:2000
                          })
                          resolve()
                        }
                      })
                      
                  },
                  fail(res){
                    wx.showToast({
                      title:"授权失败",
                      icon:"error"
                    })
                    reject()
                  }
                })
        }
      }
    })
      
    })
  }
//检查登录状态
async function checkLogin(){
if(app.globalData.userInfo==null){
  return await login();
}else{
  return true
}
}
module.exports = {
  formatTime,
  login:login,
  checkLogin:checkLogin // 前面一个是外部引用时使用的名称， 后一个是本js中变量的名称
}
